package middleware

import (
	"fmt"

	"gitee.com/daledi/public/options"
	"github.com/gofiber/fiber"
	"github.com/pkg/errors"
)

func PanicHandler(c *fiber.Ctx) (err error) {
	defer func() {
		if err := recover(); err != nil {
			options.GolbalConf.ErrLog.Printf("[Recovery] Request: %s\n", string(c.Context().Request.Header.Header()))
			options.GolbalConf.ErrLog.Printf("[Recovery] Error: %+v\n", errors.Errorf("%v", err))
		}
	}()
	return c.Next()
}

func ErrorHandler(c *fiber.Ctx, err error) error {
	var lerr error
	if e, ok := err.(*fiber.Error); ok {
		lerr = c.JSON(e)
	} else {
		lerr = c.JSON(&fiber.Error{
			Code:    -99999,
			Message: fmt.Sprintf("未知的错误信息：%+v", err),
		})
	}
	return lerr
}
